package com.moss.common.util;

import com.moss.common.exception.UploadImageBedException;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * @ClassName 配置码云图床信息
 * @Author gxcc3
 * @Date 2024/09/02 15:38
 * @Description 上传Gitee图床工具类
 */
public class GiteeImageBedUtil {


    protected static final Logger log = LoggerFactory.getLogger(GiteeImageBedUtil.class);


    /**
     * 码云私人令牌
     */
    public static final String ACCESS_TOKEN = "4358504955dd4be6493a4085faf8225c";  //这里不展示我自己的了，需要你自己补充

    /**
     * 码云个人空间名，改成自己的，如果不知道个人空间名可以看下面的图片
     */
    public static final String OWNER = "gxcc3";

    /**
     * 上传指定仓库，改成自己创建的图床仓库
     */
    public static final String REPO = "gxcc3-image";


    /**
     * 上传时指定存放图片路径
     */
    public static final String PATH = "detection-image"; //使用到了日期工具类


    /**
     * 用于提交描述
     */
    public static final String ADD_MESSAGE = "add img";
    public static final String DEL_MESSAGE = "DEL img";

    //API
    /**
     * 新建(POST)、获取(GET)、删除(DELETE)文件：()中指的是使用对应的请求方式
     * %s =>仓库所属空间地址(企业、组织或个人的地址path)  (owner)
     * %s => 仓库路径(repo)
     * %s => 文件的路径(path)
     */
    public static final String API_CREATE_POST = "https://gitee.com/api/v5/repos/%s/%s/contents/%s";


    /**
     * 图片访问前缀
     */
    private static final String PRE = "https://gitee.com/" + OWNER + "/" + REPO + "/raw/master/";

    /**
     * 新建(POST)、获取(GET)、删除(DELETE)文件：()中指的是使用对应的请求方式
     * %s =>仓库所属空间地址(企业、组织或个人的地址path)  (owner)
     * %s => 仓库路径(repo)
     * %s => 文件的路径(path)
     */


    /**
     * 生成创建(获取、删除)的指定文件路径
     *
     * @param originalFilename
     * @return
     */
    public static String createUploadFileUrl(String originalFilename) {
        //获取文件后缀
        String suffix = FileUtils.getFileSuffix(originalFilename);//使用到了自己编写的FileUtils工具类
        //拼接存储的图片名称
        String fileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + suffix;
        //填充请求路径
        return String.format(GiteeImageBedUtil.API_CREATE_POST,
                GiteeImageBedUtil.OWNER,
                GiteeImageBedUtil.REPO,
                GiteeImageBedUtil.PATH + "/" + fileName);
    }




    /**
     * 获取创建文件的请求体map集合：access_token、message、content
     *
     * @param multipartFile 文件字节数组
     * @return 封装成map的请求体集合
     */
    public static Map<String, String> getUploadBodyMap(byte[] multipartFile) {
        HashMap<String, String> bodyMap = new HashMap<>(3);
        bodyMap.put("access_token", GiteeImageBedUtil.ACCESS_TOKEN);
        bodyMap.put("message", GiteeImageBedUtil.ADD_MESSAGE);
        bodyMap.put("content", Base64.encode(multipartFile));
        return bodyMap;
    }

    public static String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)){
            throw new UploadImageBedException("图片上传失败-文件错误");
        }
        //获取文件后缀
        String suffix = FileUtils.getFileSuffix(originalFilename);//使用到了自己编写的FileUtils工具类
        //拼接存储的图片名称

        String fileName = IdUtil.randomDateId() + suffix;
        //填充请求路径
        String uploadUrl = String.format(GiteeImageBedUtil.API_CREATE_POST,
                GiteeImageBedUtil.OWNER,
                GiteeImageBedUtil.REPO,
                GiteeImageBedUtil.PATH + "/" + fileName);

        //根据文件名生成指定的请求url
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(uploadUrl);

        Map<String, String> uploadBodyMap = null;
        try {
            uploadBodyMap = GiteeImageBedUtil.getUploadBodyMap(file.getBytes());
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (Map.Entry<String, String> entry : uploadBodyMap.entrySet()) {
                builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.TEXT_PLAIN);
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            log.info("上传图片-返回结果-[{}]", EntityUtils.toString(response.getEntity()));
            httpClient.close();
            return PRE + PATH + "/" + fileName;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
